//
//  VideoManView.swift
//  TestConcurreces
//
//  Created by rolodestar on 2025/6/16.
//

import SwiftUI
import SwiftData
import RoSwiftDataForNetVideoDownload
import RoNetApiLibrary
import BilibiliSearch

struct VideoManView: View {
    @EnvironmentObject var actor: VideoActor
    @Environment(\.modelContext) var modelContext
    @Query var videos:[BeautyModel]
    @Query var biliVideos:[BilibiliNetVideo] {
        didSet {
            biliVideos.sort { (video1, video2) -> Bool in
                if let localUrl1 = video1.localUrl, localUrl2 == nil {
                    return true
                } else if localUrl1 == nil, let localUrl2 = video2.localUrl {
                    return false
                } else {
                    return false
                }
            }
        }
    }
    @State var selectedVideo: BeautyModel?
    @State var selectedBiliVideo: BilibiliNetVideo?
    @State var keyword:String = ""
    @State var alertString: String? = nil
    @State var isSearchingBili: Bool = false
    var body: some View {
        NavigationSplitView {
            List{
                ForEach(videos) {video in
                    VideoListItemView(video: video)
                        .padding(5)
                        .background(Color.gray.opacity(0.1))
                        .foregroundColor(.black)
                        .cornerRadius(10)
                        .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                        .onTapGesture {
                            self.selectedVideo = video
                            self.selectedBiliVideo = nil
                        }
                }
                Divider()
                ForEach(biliVideos.sorted { (video1, video2) -> Bool in
                    if let _ = video1.localUrl, video2.localUrl == nil {
                        return true
                    } else if video1.localUrl == nil,let  _ = video2.localUrl {
                        return false
                    } else {
                        return false
                    }
                }) {video in
                    BiliVideoListItemView(video: video)
                        .padding(5)
                        .background(Color.gray.opacity(0.1))
                        .foregroundColor(.black)
                        .cornerRadius(10)
                        .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                        .onTapGesture {
                            self.selectedVideo = nil
                            self.selectedBiliVideo = video
                        }
                }
            }
            .listRowInsets(EdgeInsets())
            .background(Color.white)
        } detail: {
            if(selectedVideo == nil && selectedBiliVideo == nil){
                Text("not select video")
                    .font(.title)
                    .foregroundColor(.secondary)
            }else if selectedVideo != nil{
                VideoDetailVew(video: selectedVideo!)
            }else if selectedBiliVideo != nil{
                BiliVideoDetailVew( video: selectedBiliVideo!)
            }
        }
        .toolbar {
            ToolbarItem{
                TextField("输入关键字",text: $keyword)
                    .frame(width: 100)
            }
            ToolbarItem{
                if isSearchingBili{
                    HStack{
                        Text("正在搜索")
                        ProgressView()
                            .progressViewStyle(.circular)
                    }
                }
                
            }
            ToolbarItem {
                Button("搜索bilibili"){
                    if keyword.isEmpty{
                        return
                    }
                    isSearchingBili = true
                    Task{
                        let parsings = await  BilibiliSearchStore.fetchVideos(keyword: keyword)
                        await MainActor.run{
                            do{
                                for parsing in parsings{
                                    let biliNetVideo = BilibiliNetVideo.createModel(from: parsing)
                                    self.modelContext.insert(biliNetVideo)
                                }
                                
                                try self.modelContext.save()
                                //                            await MainActor.run{
                                self.isSearchingBili = false
                                //                            }
                            }catch{
                                print(error)
                            }
                        }
                    }
                }
            }
            ToolbarItem {
                Button("添加短视频"){
                    
                    
                    Task{
                        if let address = await RoNetApiLibrary.shared.fetchBeautyGirlVideoToNetAddress(){
                            let beauty = BeautyModel(id: UUID(), remoteUrl: address)
                            try await MainActor.run{
                                self.modelContext.insert(beauty)
                                try self.modelContext.save()
                            }
                            try await actor.appendNewVideoAndDownload(id: beauty.persistentModelID)
                        }
                    }
                }
            }
            
            ToolbarItem {
                if(selectedBiliVideo != nil){
                    Button("删除当前bili"){
                        Task{
                            if (selectedBiliVideo!.localUrl != nil){
                                try FileManager.default.removeItem(at: selectedBiliVideo!.localUrl!)
                            }
                            self.modelContext.delete(selectedBiliVideo!)
                            try self.modelContext.save()
                            self.selectedBiliVideo = nil
                        }
                        
                        
                    }.foregroundStyle(.red)
                }
            }
            
            ToolbarItem {
                Button("清空bili库"){
                    do{
                        for bili in biliVideos{
                            self.modelContext.delete(bili)
                        }
                        try self.modelContext.save()
                    }catch{
                        print(error)
                    }
                }
            }
                ToolbarItem{
                    Button("一键清空未下载视频") {
                        do {
                            for bili in biliVideos.filter({ $0.localUrl == nil }) {
                                self.modelContext.delete(bili)
                            }
                            for video in videos.filter({ $0.localUrl == nil }) {
                                self.modelContext.delete(video)
                            }
                            try self.modelContext.save()
                        } catch {
                            print(error)
                        }
                    }
                    .padding()
                
            }
        }
        
    }
}

#Preview {
    VideoManView()
}
